<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" name="" id="" placeholder="请输入你想要说的内容">
    <button class="send">发送信息</button>
    <button class="close">关闭</button>
    <div class="content"></div>
    <script>
        let content = document.querySelector(".content")

        // 建立连接
        let ws = new WebSocket("wss://echo.websocket.org")

        ws.onopen = function () {
            content.innerHTML = "<span style='color:red'>服务已连接成功</span>" + "<br>"
        }


        document.querySelector(".send").onclick = function () {

            ws.send(document.querySelector("input").value)
            content.innerHTML += `客户端：<span>${document.querySelector("input").value}</span>` + "<br>"

        }


        ws.onmessage = function (event) {
            content.innerHTML += `服务器：<span>${event.data}</span>` + "<br>"

        }


        document.querySelector(".close").onclick = function () {
            ws.close()
        };

        ws.onclose = function () {
            content.innerHTML = "<span style='color:red'>链接关闭</span>" + "<br>"
        }


    </script>
</body>

</html>